import {Component, ElementRef, EventEmitter, Input, OnInit, Output, ViewChild} from '@angular/core';
import {HttpService} from '@kylin/http';
import {NzMessageService} from 'ng-zorro-antd';
import {HttpClient} from '@angular/common/http';

@Component({
    selector: 'kylin-feature-filter',
    templateUrl: './feature-filter.component.html',
    styleUrls: ['./feature-filter.component.less']
})
export class FeatureFilterComponent implements OnInit {
    @Input() isVisible: boolean;
    @Output() isVisibleChange = new EventEmitter();
    @Input() layerId: string;
    @Input() allProps: Array<any>;
    @Output() filterDone = new EventEmitter();
    @ViewChild('sqlTextarea', {static: false}) sqlTextarea: ElementRef;
    logicalBtns = [
        {key: ' = ', label: '='},
        {key: ' <> ', label: '<>'},
        {key: ' like() ', label: 'Like'},
        {key: '>', label: '>'},
        {key: '>=', label: '>='},
        {key: ' and() ', label: 'And'},
        {key: ' < ', label: '<'},
        {key: ' <= ', label: '<='},
        {key: ' or() ', label: 'Or'},
        {key: ' _ ', label: '_'},
        {key: ' % ', label: '%'},
        {key: ' () ', label: '()'},
        {key: ' not() ', label: 'Not'},
        {key: ' is() ', label: 'Is'},
    ];
    currentProp: string;
    currentVal: string;
    applyLoading = false;
    uniqueValues = new Array<any>();
    valuesLoading = false;
    sqlString = '';
    setCurrentValueTimer: any;
    setCurrentPropTimer: any;

    constructor(private http: HttpService, private message: NzMessageService, private ngHttp: HttpClient) {
    }

    ngOnInit() {
    }

    applyFilter() {
        this.checkSql();
    }

    checkSql() {
        this.applyLoading = true;
        this.http.get('/layer/shpPropertyAll', {
            layerId: this.layerId,
            sql: this.sqlString,
            current: '1',
            size: '10'
        }).then(rep => {
            this.applyLoading = false;
            if (rep.resp_code === '10000') {
                this.filterDone.emit(this.sqlString);
                this.handleCancel();
            }
        }).catch(err => {
            this.applyLoading = false;
            this.message.error('无效SQL语句，请重新输入');
        });
    }

    clearFilter() {
        this.currentProp = null;
        this.currentVal = null;
        this.uniqueValues = null;
        this.sqlString = null;
    }

    handleCancel() {
        this.isVisible = false;
        this.isVisibleChange.emit(false)
    }

    getUniqueValues() {
        if (!this.currentProp) {
            return;
        }
        this.valuesLoading = true;
        this.http.get('/layer/shpPropertyValue', {
            layerId: this.layerId,
            property: this.currentProp
        }).then(rep => {
            this.valuesLoading = false;
            if (rep.resp_code === '10000') {
                this.uniqueValues = rep.data;
            } else {
                this.message.error('获取数据失败，' + rep.resp_msg);
            }
        })
    }

    writeSqlByBtn(btnInfo: any) {
        this.writeSqlString(btnInfo.key, 'byBtn');
    }

    setCurrentProp(prop: string) {
        if (this.setCurrentPropTimer) {
            clearTimeout(this.setCurrentPropTimer);
            this.setCurrentPropTimer = null;
        }
        this.setCurrentPropTimer = setTimeout(() => {
            this.setCurrentPropTimer = null;
            this.currentProp = prop;
            this.uniqueValues = null;
        }, 300);
    }

    writeSqlByProp(prop: string) {
        if (this.setCurrentPropTimer) {
            clearTimeout(this.setCurrentPropTimer);
            this.setCurrentPropTimer = null;
        }
        this.writeSqlString('\"' + prop + '\"');
    }

    setCurrentValue(value: string) {
        if (this.setCurrentValueTimer) {
            clearTimeout(this.setCurrentValueTimer);
            this.setCurrentValueTimer = null;
        }
        this.setCurrentValueTimer = setTimeout(() => {
            this.currentVal = value;
            this.setCurrentValueTimer = null;
        }, 300);
    }

    writeSqlByValue(value: string) {
        if (this.setCurrentValueTimer) {
            clearTimeout(this.setCurrentValueTimer);
            this.setCurrentValueTimer = null;
        }
        this.writeSqlString('\'' + value + '\'');
    }

    writeSqlString(newPart, method?: string) {
        const start = this.sqlTextarea.nativeElement.selectionStart;
        const end = this.sqlTextarea.nativeElement.selectionEnd;
        this.sqlString = this.sqlString.substring(0, start) + newPart + this.sqlString.substring(end, this.sqlString.length);
        setTimeout(() => {
            if (newPart.indexOf('()') !== -1 && method === 'byBtn') {
                this.sqlTextarea.nativeElement.selectionStart = start + newPart.length - 2;
                this.sqlTextarea.nativeElement.selectionEnd = start + newPart.length - 2;
            } else {
                this.sqlTextarea.nativeElement.selectionStart = start + newPart.length;
                this.sqlTextarea.nativeElement.selectionEnd = start + newPart.length;
            }
            this.sqlTextarea.nativeElement.focus()
        }, 0);
    }
}
